package com.dn.designpatterns.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: designpatterns
 * @description: 动态代理
 * @author: DN
 * @create: 2021-04-01 22:09
 **/
public class DynamicProxy implements InvocationHandler {
    // 动态代理
    private Object obj;
    DynamicProxy(Object obj) {
        this.obj = obj;
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("方法执行前...");
        method.invoke(obj,args);
        System.out.println("方法执行后...");
        return null;
    }


    public static void main(String[] args) {
        AbstractSubject subject = null;
        InvocationHandler handler = null;
        handler = new DynamicProxy(new RealSubject1());
        subject = (AbstractSubject) Proxy.newProxyInstance(AbstractSubject.class.getClassLoader(),new Class[]{AbstractSubject.class},handler);
        subject.request();

    }



}

// 抽象主题
interface AbstractSubject {
    void request();
}

// 真实主题1
class RealSubject1 implements AbstractSubject{
    public void request() {
        System.out.println("真实主题1...");
    }
}
// 真实主题2
class RealSubject2 implements AbstractSubject{
    public void request() {
        System.out.println("真实主题2...");
    }
}

interface A {
    void gets();
}

class B implements A {
    private String s;

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    public void gets() {
        System.out.println(s);
    }
}